package com.sky.task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class OrderTask {

    @Autowired
    private OrderMapper orderMapper;

    /**
     * 每分钟执行一次
     */
    @Scheduled(cron = "0 0/1 * * * ?")
//    @Scheduled(cron = "0/5 * * * * ?")
    public void payOrderLongTime(){
        // 1.查询未支付和下单超过15分钟的所有订单列表List<Orders>
        // 查找订单：select * from orders where pay_status = 0 and order_time < now() - 15 minutes
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.findByLongTime(Orders.UN_PAID,orderTime);

        // 2.列表List<Orders>不为空，说明存在超时未支付订单
        if(ordersList == null || ordersList.size() == 0){
            log.info("当前没有超时未支付订单");
            return;
        }

        // 3.遍历List<Orders>，将所有超时未支付订单的支付状态修改为已取消
        for (Orders orders : ordersList) {
            orders.setStatus(Orders.CANCELLED);
            orders.setCancelTime(LocalDateTime.now());
            orders.setCancelReason("订单超时未支付，已取消");
            log.info("订单号:{}，订单状态修改为已取消", orders.getNumber());
            // 调用mapper更新
            orderMapper.update(orders);
        }
    }

    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrder(){

        // 1.查询所有派送中和1个小时前的订单
        // select * from orders where status = 4 and order_time < now() - 1 hour
        LocalDateTime orderTime = LocalDateTime.now().plusMinutes(-60);
        List<Orders> ordersList = orderMapper.findByDeliveryOrder(Orders.DELIVERY_IN_PROGRESS,orderTime);

        // 2.列表集合List<Orders>如果为null,不存在订单，结束
        if(ordersList == null || ordersList.size() == 0){
            log.info("当前没有派送中订单");
            return;
        }

        // 3.遍历List<Orders>，将所有派送中订单的支付状态修改为已完成
        ordersList.forEach(orders -> {
            orders.setStatus(Orders.COMPLETED);
            orderMapper.update(orders);
        });

    }
}
